const express = require('express')
const router = express.Router()
const auth = require('../middleware/auth')
const memberService = require('../services/memberService')
const logger = require('../utils/logger')

/**
 * 获取所有会员等级
 * GET /api/members/levels
 */
router.get('/levels', async (req, res) => {
  try {
    const levels = await memberService.getAllLevels()

    res.json({
      success: true,
      code: 200,
      message: '获取会员等级成功',
      data: levels
    })
  } catch (error) {
    logger.error('获取会员等级失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取会员等级失败'
    })
  }
})

/**
 * 获取用户会员信息
 * GET /api/members/info
 */
router.get('/info', auth, async (req, res) => {
  try {
    const memberInfo = await memberService.getUserMemberInfo(req.user.id)

    res.json({
      success: true,
      code: 200,
      message: '获取会员信息成功',
      data: memberInfo
    })
  } catch (error) {
    logger.error('获取会员信息失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取会员信息失败'
    })
  }
})

/**
 * 检查并更新用户会员等级
 * POST /api/members/check-upgrade
 */
router.post('/check-upgrade', auth, async (req, res) => {
  try {
    const result = await memberService.checkAndUpdateMemberLevel(req.user.id)

    res.json({
      success: true,
      code: 200,
      message: result.upgraded ? '会员等级升级成功' : '会员等级无变化',
      data: result
    })
  } catch (error) {
    logger.error('检查会员等级升级失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '检查会员等级升级失败'
    })
  }
})

/**
 * 获取用户升级历史
 * GET /api/members/upgrade-history
 */
router.get('/upgrade-history', auth, async (req, res) => {
  try {
    const {
      page,
      limit
    } = req.query

    const options = {
      page: page ? parseInt(page) : undefined,
      limit: limit ? parseInt(limit) : undefined
    }

    const result = await memberService.getUserUpgradeHistory(req.user.id, options)

    res.json({
      success: true,
      code: 200,
      message: '获取升级历史成功',
      data: result
    })
  } catch (error) {
    logger.error('获取升级历史失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取升级历史失败'
    })
  }
})

/**
 * 计算订单折扣
 * POST /api/members/calculate-discount
 */
router.post('/calculate-discount', auth, async (req, res) => {
  try {
    const { originalAmount } = req.body

    if (!originalAmount || originalAmount <= 0) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '原始金额无效'
      })
    }

    const discount = await memberService.calculateOrderDiscount(req.user.id, originalAmount)

    res.json({
      success: true,
      code: 200,
      message: '计算折扣成功',
      data: discount
    })
  } catch (error) {
    logger.error('计算订单折扣失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '计算订单折扣失败'
    })
  }
})

/**
 * 获取会员统计信息
 * GET /api/members/statistics
 */
router.get('/statistics', async (req, res) => {
  try {
    const statistics = await memberService.getMemberStatistics()

    res.json({
      success: true,
      code: 200,
      message: '获取会员统计成功',
      data: statistics
    })
  } catch (error) {
    logger.error('获取会员统计失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取会员统计失败'
    })
  }
})

module.exports = router